/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        
        vector<int> ret;
        if(nullptr==root){

            return ret;
        }
        stack<TreeNode*> q;
        TreeNode* cur=root,*pre=nullptr;

        while(nullptr!=cur || q.size()){

            while(cur){

                q.push(cur);
                cur=cur->left;
            }
            TreeNode* t=q.top();
            if(t->right==nullptr || pre==t->right){

                ret.push_back(t->val);
                q.pop();
                pre=t;
            }
            else{

                cur=t->right;
            }
        }

        return ret;
    }
};
